import * as path from 'path';
import * as os from 'os';
import * as md5 from 'md5';
import * as fs from 'fs';

/**
 * 获得配置文件中的 keys
 * @returns
 */
const getKeys = () => {
  const configFile = path.join(__dirname, '../config/config.default.js');
  const configContent = fs.readFileSync(configFile, 'utf8');
  const keys = configContent.match(/keys: '([^']+)'/)?.[1];
  return keys;
};

/**
 * 项目数据目录
 * @returns
 */
export const pDataPath = () => {
  const dirPath = path.join(os.homedir(), '.cool-admin', md5(getKeys()));
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
  return dirPath;
};

/**
 * 上传目录
 * @returns
 */
export const pUploadPath = () => {
  // 优先使用环境变量 UPLOAD_PATH
  let uploadPath = process.env.UPLOAD_PATH;
  
  if (!uploadPath) {
    // 方案1: 使用项目根目录下的 uploads 文件夹
    uploadPath = path.join(__dirname, '..', '..', 'uploads');
    
    // 方案2: 使用自定义绝对路径（取消注释并修改路径）
    // uploadPath = 'D:\\MyUploads';
    
    // 方案3: 仍使用用户目录，但改名（取消注释）
    // uploadPath = path.join(os.homedir(), 'MyAppUploads');
    
    // 方案4: 恢复原来的 .cool-admin 路径（取消注释）
    // uploadPath = path.join(pDataPath(), 'upload');
  }
  
  if (!fs.existsSync(uploadPath)) {
    fs.mkdirSync(uploadPath, { recursive: true });
  }
  return uploadPath;
};

/**
 * 插件目录
 * @returns
 */
export const pPluginPath = () => {
  const pluginPath = path.join(pDataPath(), 'plugin');
  if (!fs.existsSync(pluginPath)) {
    fs.mkdirSync(pluginPath, { recursive: true });
  }
  return pluginPath;
};

/**
 * sqlite 数据库文件
 */
export const pSqlitePath = () => {
  return path.join(pDataPath(), 'cool.sqlite');
};

/**
 * 缓存目录
 * @returns
 */
export const pCachePath = () => {
  return path.join(pDataPath(), 'cache');
};
